package com.cui.project.controller;

import com.api.common.model.entity.InterfaceInfo;
import com.api.common.model.entity.User;
import com.api.common.model.entity.UserInterfaceInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cui.project.constant.UserConstant;
import com.cui.project.exception.BusinessException;
import com.cui.project.mapper.UserInterfaceInfoMapper;
import com.cui.project.model.vo.InterfaceInfoVO;
import com.cui.project.service.InterfaceInfoService;
import com.cui.project.annotation.AuthCheck;
import com.api.common.common.BaseResponse;
import com.api.common.common.ErrorCode;
import com.api.common.common.ResultUtils;
import com.cui.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: 崔老爷
 * Date: 2024/9/29 12:33
 * @Description:
 */
@RestController
@RequestMapping("/analysis")
@Slf4j
public class AnalysisController {


    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @GetMapping("/top/interface/invoke")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<InterfaceInfoVO>> listTopInvokeInterface(
            @RequestParam(required = true,defaultValue = "3") Integer size,
            @RequestParam Integer type,
            HttpServletRequest request) {
        TrafficForecastController.AnalysisTypeEnum analysisEnum = TrafficForecastController.AnalysisTypeEnum.get(type);
        if(analysisEnum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未知，type="+type);
        }

        User user = userService.getLoginUser(request);
        Long userId = user.getId();

        // 查询调用次数最多的接口信息列表
        List<UserInterfaceInfo> userInterfaceInfoList =null;
        if(TrafficForecastController.AnalysisTypeEnum.use.getType().equals(type)){
            userInterfaceInfoList=userInterfaceInfoMapper.listTopInvokeInterface(size,userId);
        }else if(TrafficForecastController.AnalysisTypeEnum.all.getType().equals(type)){
            if (!userService.isAdmin(request)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            userInterfaceInfoList=userInterfaceInfoMapper.listTopInvokeInterface(size,null);
        }else if(TrafficForecastController.AnalysisTypeEnum.upload.getType().equals(type)){
            userInterfaceInfoList=userInterfaceInfoMapper.listTopInvokeInterface(size,userId);
        }else{
            userInterfaceInfoList=Collections.emptyList();
        }

        if(userInterfaceInfoList.isEmpty()){
            return ResultUtils.success(Collections.emptyList());
        }

        // 将接口信息按照接口ID分组，便于关联查询
        Map<Long, List<UserInterfaceInfo>> interfaceInfoIdObjMap = userInterfaceInfoList.stream()
                .collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));
        // 创建查询接口信息的条件包装器
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        // 设置查询条件，使用接口信息ID在接口信息映射中的键集合进行条件匹配
        queryWrapper.in("id", interfaceInfoIdObjMap.keySet()).select("id","name");
        // 调用接口信息服务的list方法，传入条件包装器，获取符合条件的接口信息列表
        List<InterfaceInfo> list = interfaceInfoService.list(queryWrapper);
        // 判断查询结果是否为空
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        // 构建接口信息VO列表，使用流式处理将接口信息映射为接口信息VO对象，并加入列表中
        List<InterfaceInfoVO> interfaceInfoVOList = list.stream().map(interfaceInfo -> {
            // 创建一个新的接口信息VO对象
            InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
            // 将接口信息复制到接口信息VO对象中
            BeanUtils.copyProperties(interfaceInfo, interfaceInfoVO);
            // 从接口信息ID对应的映射中获取调用次数
            int totalNum = interfaceInfoIdObjMap.get(interfaceInfo.getId()).get(0).getTotalNum();
            // 将调用次数设置到接口信息VO对象中
            interfaceInfoVO.setTotalNum(totalNum);
            // 返回构建好的接口信息VO对象
            return interfaceInfoVO;
        }).collect(Collectors.toList());
        // 返回处理结果
        return ResultUtils.success(interfaceInfoVOList);
    }
}
